package com.bill99.test;

public class SKUProductGenerater {

	private static final String SPLIT_STR = "\\|";

	public static void main(String[] args) {

		SKUProductGenerater pg = new SKUProductGenerater();
		pg.generate("abc|d|efghi");

	}

	public String[] generate(String s) {
		String[] skus = s.split(SPLIT_STR);
		// the array like the some skus
		char[][] skuDetails = splitStringToChar(skus);
		// record sku generated status
		int[] skuStatus = createFlags(skus.length);
		int productTotal = countProductTotal(skuDetails);
		String[] products = new String[productTotal];
		fillProductsBySkuDetails(skuDetails, skuStatus, products);
		return new String[] {};
	}

	private char[][] splitStringToChar(String[] sarr) {
		char[][] carrs = new char[sarr.length][];
		for (int i = 0, n = sarr.length; i < n; i++) {
			String s = sarr[i];
			carrs[i] = s.toCharArray();
		}
		return carrs;

	}

	private int[] createFlags(int length) {
		int[] flags = new int[length];
		initFlags(flags);
		return flags;
	}

	private void initFlags(int[] flags) {
		for (int i = 0, n = flags.length; i < n; i++) {
			flags[i] = 0;
		}
	}

	private int countProductTotal(char[][] skuDetails) {
		int count = 1;
		for (char[] cs : skuDetails) {
			count *= cs.length;
		}
		return count;
	}

	private void fillProductsBySkuDetails(char[][] skuDetails, int[] skuStatus, String[] products) {
		int skuTotal = skuDetails.length;
		int productTotal = products.length;
		for (int ipro = 0; ipro < productTotal; ipro++) {
			StringBuffer productSku = new StringBuffer(skuTotal);
			for (int isku = 0; isku < skuTotal; isku++) {
				productSku.append(skuDetails[isku][skuStatus[isku]]);
			}
			updateSkuStatus(skuDetails, skuStatus, 0, skuTotal);
		}
	}

	// skuStatus is like a number, and every updating it add one step.

	private void updateSkuStatus(char[][] skuDetails, int[] skuStatus, int index, int skuTotal) {
		// when no sku to update
		if (index == skuTotal)
			return;
		skuStatus[index] = skuStatus[index] + 1;
		if (skuStatus[index] >= skuDetails[index].length) {
			skuStatus[index] = 0;
			updateSkuStatus(skuDetails, skuStatus, index + 1, skuTotal);
		}
	}

}